/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import server.TranslatorServer;

/**
 * The client for the translator application.
 * Allows the user to input words to translate
 * @author Luuk
 */
public class TranslatorClient{
    
    /**
     * Launches the clientGUI.
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new ClientGUI().Launch();
    }
    
    /**
     * Translates a word via the translationserver.
     * @param text, the word that has to be translated.
     * @return the tranlated word.
     */
    public static String translate(String text){
        try {
            Socket sock = new Socket("LAPTOP2", TranslatorServer.PORT);
            PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
            out.println(text);
            BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String response;
            while((response = br.readLine()) != null){
                return processResponse(response);
            }
            out.close();
            sock.close();
        } catch (UnknownHostException ex) {
            Logger.getLogger(TranslatorClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TranslatorClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }
    
    public static String processResponse(String response){
        String[] input = response.split(";");
        Pattern pattern = Pattern.compile("translated:(.+)");
        Matcher matcher = pattern.matcher(input[1].toLowerCase());
        matcher.find();
        return matcher.group(1);
    }
}
